********************************************************************************
* clean_mna_firm.do
* Purpose: Create a panel of ALL M&A firms (both acquirers and targets)
*          across all deal years, merging firm account data with deal information.
*
* This dataset is used for Figure 1, which plots the number of M&A deals
* per year and the share that are in the matched sample.
*
* Logic: For each year, take the firm-level NALMF data (firm_YYYY.dta),
*        drop first_mna variables already in firm_YYYY, then re-merge with
*        all_mna (all deals, not just first events) to create a panel where
*        each observation is a firm x deal x year combination.
*
* Input:
*   $data/firm_YYYY.dta   - Annual firm data (from clean_firm.do)
*   $data/all_mna.dta     - All completed M&A deals (from clean_mna.do)
*
* Output:
*   $data/NALMF_mna.dta   - Panel of M&A firm x deal x year observations
********************************************************************************

//------------------------------------------------------------------------------
// SECTION 1: BUILD ANNUAL M&A FIRM DATASETS
//
// For each year, merge the firm account data with the full M&A deal list.
// Using merge 1:m (firm to many deals) to handle firms involved in multiple deals.
// keep(3) retains only matched observations (M&A firms only).
//------------------------------------------------------------------------------
forvalues y = 2001/2017 {

	use $data/firm_`y', clear

	* Drop the first_mna variables already embedded in firm_YYYY.dta
	* (these reflect only the FIRST deal per firm, but here we want ALL deals)
	drop Acquirer DEAL DEAL_YEAR other_party_id within_all merger

	* Merge firm accounts with all M&A deals (acquirer or target in any deal)
	merge 1:m entid_syn using $data/all_mna, keepusing(DEAL DEAL_YEAR Acquirer) keep(3) nogen

	save $data/NALMF_mna_`y', replace
}

//------------------------------------------------------------------------------
// SECTION 2: STACK ANNUAL FILES INTO A SINGLE PANEL
//------------------------------------------------------------------------------
drop _all
forvalues y = 2001/2017 {
	append using $data/NALMF_mna_`y', force
	* Remove the temporary annual file after appending
	rm $data/NALMF_mna_`y'.dta
}

compress
save $data/NALMF_mna, replace
